from flask import Blueprint, g

from controller.role import add_role_info, get_roles, role_enable_status, get_role_info, get_role_permission, \
    change_role_permission
from utils.permission import authorize
from utils.views import valid, resp_with_data
from components.base_exception import ParamsError
from components.base_log import log_method_call

role_bp = Blueprint('role', __name__)


@role_bp.route('/add_role', methods=['POST'])
@authorize("system:role:add")
@log_method_call(action='Create')
def add_role():
    name = g.json.get('name')
    valid_res = valid(
        (name, '姓名必填'),
    )
    if valid_res:
        raise ParamsError(data=valid_res)
    add_role_info()
    return resp_with_data(10000)


@role_bp.route('/roles', methods=['GET'])
@authorize("system:*:*")
@log_method_call(action='Retrieve')
def roles():
    data = get_roles()
    return resp_with_data(10000, data)


@role_bp.route('/enable_role', methods=['POST'])
@authorize("system:role:update")
@log_method_call(action='Update')
def enable_role():
    role_id = g.json.get('role_id')
    valid_res = valid(
        (role_id, '角色id必填'),
    )
    if valid_res:
        raise ParamsError(data=valid_res)
    role_enable_status(True)
    return resp_with_data(10000)


@role_bp.route('/disable_role', methods=['POST'])
@authorize("system:role:update")
@log_method_call(action='Update')
def disable_role():
    role_id = g.json.get('role_id')
    valid_res = valid(
        (role_id, '角色id必填'),
    )
    if valid_res:
        raise ParamsError(data=valid_res)
    role_enable_status(False)
    return resp_with_data(10000)


@role_bp.route('/role_info/<pk>', methods=['GET'])
@authorize("system:*:*")
@log_method_call(action='Retrieve')
def role_info(pk):
    data = get_role_info(pk)
    return resp_with_data(10000, data)


@role_bp.route('/auths/<pk>', methods=['GET'])
@authorize("system:role:update")
@log_method_call(action='Retrieve')
def role_permission(pk):
    data = get_role_permission(pk)
    return resp_with_data(10000, data)


@role_bp.route('/update_auth', methods=['POST'])
@authorize("system:role:update")
@log_method_call(action='Update')
def update_role_permission():
    id_list = g.json.get('id_list')
    role_id = g.json.get('role_id')
    valid_res = valid(
        (id_list, '权限id表必填'),
        (role_id, '角色id必填')
    )
    if valid_res:
        raise ParamsError(data=valid_res)
    change_role_permission()
    return resp_with_data(10000)
